﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;

namespace CoreApp
{
    /// <summary>
    /// 微信模板消息帮助类
    /// </summary>
    public class WxTemplateMessageHelper
    {

        string _AccessToken=string.Empty;

        public WxTemplateMessageHelper(string AccessToken)
        {
            _AccessToken = AccessToken;
        }


        /// <summary>
        /// 发送模版消息，
        /// </summary>
        /// <param name="openId">关注微信号《FromUserName》</param>
        /// <returns></returns>
        public string SendMsg(string openId, string formId, string page, string templateid,object data)
        {

            ///发送模版消息
            string url = string.Format("https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token={0}", _AccessToken);
            //string postData = "{ \"touser\":\"" + openId + "\",\"template_id\":\"kJxuPYYN5z915G0qtxec5fkohEVcXgw0aLfQ1PUoJhU\",\"page\":\"http://www.woizuqiu.com/Home/Index\", \"data\":{\"first\":{\"value\":\"亲，宝贝已经启程了，好想快点来到你身边!\",\"color\":\"#173177\"},\"keynote1\":{\"value\":\"201408189987\",\"color\":\"#173177\"},\"keynote2\":{\"value\":\"圆通快递\",\"color\":\"#173177\"},\"keynote3\":{\"value\":\"6522238281\",\"color\":\"#173177\"},\"remark\":{\"value\":\"点击查看完整的物流信息 。如有问题请致电XXX或直接在微信里留言，XXX将在第一时间为您服务！!\",\"color\":\"#173177\"}} }";

            WxTemplateMessage model = new WxTemplateMessage();
            model.access_token = _AccessToken;
            model.emphasis_keyword = "";
            model.data = data;
            model.form_id = formId;
            model.page = page;
            model.template_id = templateid;
            model.touser = openId;

            string strPostData = Newtonsoft.Json.JsonConvert.SerializeObject(model);

            string strJson = HttpPostData(url, strPostData);
            return strJson;
        }

        /// <summary>
        /// Post请求
        /// </summary>
        /// <param name="posturl">URL</param>
        /// <param name="postData">请求数据</param>
        /// <returns></returns>
        private string HttpPostData(string posturl, string postData)
        {
            Stream outstream = null;
            Stream instream = null;
            StreamReader sr = null;
            HttpWebResponse response = null;
            HttpWebRequest request = null;
            Encoding encoding = Encoding.UTF8;
            byte[] data = encoding.GetBytes(postData);
            // 准备请求...
            try
            {
                // 设置参数
                request = WebRequest.Create(posturl) as HttpWebRequest;
                CookieContainer cookieContainer = new CookieContainer();
                request.CookieContainer = cookieContainer;
                request.AllowAutoRedirect = true;
                request.Method = "POST";
                request.ContentType = "application/x-www-form-urlencoded";
                request.ContentLength = data.Length;
                outstream = request.GetRequestStream();
                outstream.Write(data, 0, data.Length);
                outstream.Close();
                //发送请求并获取相应回应数据
                response = request.GetResponse() as HttpWebResponse;
                //直到request.GetResponse()程序才开始向目标网页发送Post请求
                instream = response.GetResponseStream();
                sr = new StreamReader(instream, encoding);
                //返回结果网页（html）代码
                string content = sr.ReadToEnd();
                string err = string.Empty;
                //Response.Write(content);
                return content;
            }
            catch (Exception ex)
            {
                string err = ex.Message;
                return string.Empty;
            }
        }

    }
}
